package service

import (
	"encoding/json"
	"github.com/google/wire"
	"go.uber.org/zap"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
)

var liveSet = wire.NewSet(wire.Struct(new(LiveList), "*"))

type LiveList struct {
	Logger *zap.Logger
}

type ResListData struct {
	DeviceSerial string `json:"deviceSerial"`
	ChannelNo    int    `json:"channelNo"`
	DeviceName   string `json:"deviceName"`
	LiveAddress  string `json:"liveAddress"`
	HdAddress    string `json:"hdAddress"`
	Rtmp         string `json:"rtmp"`
	RtmpHd       string `json:"rtmpHd"`
	FlvAddress   string `json:"flvAddress"`
	HdFlvAddress string `json:"hdFlvAddress"`
	Status       int    `json:"status"`
	Exception    int    `json:"exception"`
	BeginTime    int64  `json:"beginTime"`
	EndTime      int64  `json:"endTime"`
}

type Pages struct {
	Total int `json:"total"`
	Size  int `json:"size"`
	Page  int `json:"page"`
}

type ResBody struct {
	Msg  string        `json:"msg"`
	Code string        `json:"code"`
	Data []ResListData `json:"data"`
	Page Pages         `json:"page"`
}

type LiveUrlList struct {
	ID   int    `json:"key"`
	Name string `json:"name"`
	Url  string `json:"url"`
}

func GetLiveList(AccessToken, pageStart, pageSize string) (*ResBody, error) {
	targeturl := "https://open.ys7.com/api/lapp/live/video/list"
	forms, err := http.PostForm(targeturl, url.Values{"accessToken": {AccessToken}, "pageStart": {pageStart}, "pageSize": {pageSize}})
	if err != nil {
		return nil, err
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			return
		}
	}(forms.Body)

	body, err := ioutil.ReadAll(forms.Body)
	if err != nil {
		return nil, err
	}
	var resBody ResBody
	if err = json.Unmarshal(body, &resBody); err != nil {
		return nil, err
	}
	return &resBody, nil
}

func (l *LiveList) LiveList(token, pageStart, pageSize string) (error, *[]LiveUrlList) {
	content, err := GetLiveList(token, pageStart, pageSize)
	if err != nil {
		l.Logger.Warn("服务处理失败", zap.Error(err))
		return err, nil
	}
	var liveUrl []LiveUrlList

	for i, video := range content.Data {
		liveUrl = append(liveUrl, LiveUrlList{
			ID:   i,
			Name: video.DeviceName,
			Url:  video.Rtmp,
		})
	}
	return nil, &liveUrl
}
